/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nageoffer.shortlink.project.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化限流配置
 */
@Component
public class SentinelRuleConfig implements InitializingBean {

    /**
     * 在所有必要属性设置完成后执行此方法
     * 该方法主要用于初始化流量规则，以限制特定资源的访问频率
     * @throws Exception 如果规则加载过程中发生错误，则抛出异常
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // 创建一个空的流量规则列表
        List<FlowRule> rules = new ArrayList<>();

        // 实例化一个新的流量规则对象，用于限制订单创建的流量
        FlowRule createOrderRule = new FlowRule();
        // 设置该规则应用于资源"create_short-link"
        createOrderRule.setResource("create_short-link");
        // 设置规则的流量控制模式为基于QPS（每秒查询率）
        createOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置资源的最大QPS阈值为100，表示允许每秒100个请求
        createOrderRule.setCount(100);

        // 将创建的流量规则添加到规则列表中
        rules.add(createOrderRule);

        // 添加异常流量告警规则
        FlowRule alarmRule = new FlowRule();
        alarmRule.setResource("create_short-link");
        alarmRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        alarmRule.setCount(100);
        alarmRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
        alarmRule.setMaxQueueingTimeMs(1000);
        alarmRule.setLimitApp("default");
        rules.add(alarmRule);

        // 将流量规则列表加载到FlowRuleManager中，以应用这些规则
        FlowRuleManager.loadRules(rules);
    }
}
